package Manager.Account;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.concurrent.CancellationException;

import javax.swing.*;

import org.junit.runners.ParentRunner;

import Database.*;
import Exception.*;
import General.*;
import GenericClass.*;


public class PanelCreateModAccount extends JPanel
{
	private Connection connection;
	
	private JTable tableRight;
	private FormatScrollPane formatScrollPane;
	private JScrollPane scrollTable;
	private JLabel labelLogin, labelPassword, labelFirstname, labelLastname, labelManager, labelNote, labelNote2;
	private JTextField fieldLogin, fieldPassword, fieldFirstname, fieldLastname;
	private JCheckBox checkBoxManager;
	private JButton buttonDone;
	
	private String accountLogin;
	private int idAccount, manager;	

	public PanelCreateModAccount(CallDB callDB, Connection connection, int idAccount) throws CheckDataException, FormatScrollPaneException, LoadDriverException
	{
		setLayout(null);
		
		this.connection = connection;
		this.formatScrollPane = new FormatScrollPane();
		this.idAccount = idAccount;
		
		createComponent();
		showComponent();
		
		retrieveModel();
		refreshSuperRightTable();
		
		if(idAccount > 0) putInformationsIntoFields();
		
		addListeners();
	}
	
	public void createComponent() throws CheckDataException, FormatScrollPaneException
	{
		tableRight = new JTable();
		tableRight.setAutoCreateRowSorter(true);
		
		scrollTable = new JScrollPane();
		scrollTable.setBounds(410, 57, 330, 303);
		
		labelNote = new JLabel("To select classes, use MouseLeftClick + CTRL");
		labelNote.setHorizontalAlignment(SwingConstants.LEFT);
		labelNote.setBounds(420, 360, 330, 30);
		
		labelNote2 = new JLabel("If you don't want to change bound students, don't click in table");
		labelNote2.setHorizontalAlignment(SwingConstants.LEFT);
		labelNote2.setBounds(420, 380, 350, 30);

		labelLogin = new JLabel("Login");
		labelLogin.setHorizontalAlignment(SwingConstants.LEFT);
		labelLogin.setBounds(40, 57, 70, 30);
		
		fieldLogin = new JTextField("");
		fieldLogin.setColumns(10);
		fieldLogin.setHorizontalAlignment(SwingConstants.LEFT);
		fieldLogin.setBounds(115, 57, 175, 30);

		labelPassword = new JLabel("Password");
		labelPassword.setHorizontalAlignment(SwingConstants.LEFT);
		labelPassword.setBounds(40, 120, 70, 30);
		
		fieldPassword = new JTextField("");
		fieldPassword.setColumns(10);
		fieldPassword.setHorizontalAlignment(SwingConstants.LEFT);
		fieldPassword.setBounds(115, 120, 175, 30);
		
		labelFirstname = new JLabel("Firstname");
		labelFirstname.setHorizontalAlignment(SwingConstants.LEFT);
		labelFirstname.setBounds(40, 190, 70, 30);
		
		fieldFirstname = new JTextField("");
		fieldFirstname.setColumns(10);
		fieldFirstname.setHorizontalAlignment(SwingConstants.LEFT);
		fieldFirstname.setBounds(115, 190, 175, 30);
		
		labelLastname = new JLabel("Lastname");
		labelLastname.setHorizontalAlignment(SwingConstants.LEFT);
		labelLastname.setBounds(40, 260, 70, 30);
		
		fieldLastname = new JTextField("");
		fieldLastname.setColumns(10);
		fieldLastname.setHorizontalAlignment(SwingConstants.LEFT);
		fieldLastname.setBounds(115, 260, 175, 30);
		
		labelManager = new JLabel("Manager rights for this account ?");
		labelManager.setHorizontalAlignment(SwingConstants.LEFT);
		labelManager.setBounds(40, 330, 180, 30);
		
		checkBoxManager = new JCheckBox();
		checkBoxManager.setBounds(240, 330, 175, 30);
		
		buttonDone = new JButton("Done");
		buttonDone.setBounds(410, 422, 330, 45);
	}
	
	public void showComponent()
	{		
		this.add(labelLogin);		this.add(fieldLogin);
		this.add(labelPassword);	this.add(fieldPassword);
		this.add(labelFirstname);	this.add(fieldFirstname);
		this.add(labelLastname);	this.add(fieldLastname);
		this.add(labelManager);		this.add(checkBoxManager);
		
		this.add(scrollTable);
		this.add(labelNote);
		if(idAccount > 0)
			this.add(labelNote2);
		this.add(buttonDone);
		
		GraphicsSetting.setBackground(this, "image/Bg-Main.jpg", 0, 0, 800, 600);
	}
	
	private void retrieveModel() throws CheckDataException, LoadDriverException
	{
		String[] tabHeader = {"Courses"}; //Create the headers of the columns
		GeneralMethod.clearAndSetHeader(tabHeader, "right"); //Fill the arrayList by the tabHeader

		GeneralInformation.createCourseTotalModel(connection);
		GeneralMethod.setRightModel(GeneralInformation.getCourseLeftModel()); //Set the Generic Left JTable by the MyTableModel
	}
	
	protected void refreshSuperRightTable() throws FormatScrollPaneException
	{
		formatScrollPane.autoFillScrollPane(tableRight, GeneralInformation.getCourseLeftModel(), GeneralMethod.getArrayRightHeader(), scrollTable, "single", true, true, true, false);
		validate();
	}
	
	private void addListeners()
	{
		MyActionListener actionListener = new MyActionListener();
		buttonDone.addActionListener(actionListener);
	}
	
	private class MyActionListener implements ActionListener
	{
		public void actionPerformed(ActionEvent arg0)
		{
			try
			{
				if(arg0.getSource() == buttonDone)
					if(idAccount == 0)	// Creer un compte
						createAccount();
					else if(idAccount > 0) // On modifie un compte
						modifyAccount();
					else
						System.out.println("Nothing change!");
			}
			catch(InsertionDataException | CheckDataException | LoadDriverException | EraseDataException error)
			{
				TreatError.showError(error);
			}
		}
	}

	public void createAccount() throws InsertionDataException, CheckDataException, LoadDriverException
	{
		if(testFields() || verifyLogin() || tableRight.getSelectedRows().length != 0)
		{
			// Prise en compte des modifications
			int manager;
			
			if(checkBoxManager.isSelected() == true)
				manager = 1;
			else
				manager = 0;
			
			new AccountMgmt(connection).createElement(fieldLogin.getText(), fieldPassword.getText(), manager, fieldFirstname.getText(), fieldLastname.getText(), getIdClassesTab());
			
			JOptionPane.showMessageDialog(null, "Account is successfully created !", "Insertion of account", JOptionPane.INFORMATION_MESSAGE);
		}
	}
	
	public void modifyAccount() throws InsertionDataException, EraseDataException, CheckDataException, LoadDriverException
	{
		if(testFields())
		{						
			// Prise en compte des modifications
			if(checkBoxManager.isSelected() == true)
				manager = 1;
			else
				manager = 0;
			
			// On verifie s'il n'a pas changer de login => si oui on verifie son existence
			if(accountLogin.equals(fieldLogin.getText()) == false)
			{
				if(verifyLogin())
					modify();
			}
			else
				modify();
		}
	}
	
	public void modify() throws InsertionDataException, EraseDataException, CheckDataException, LoadDriverException
	{
		if(tableRight.getSelectedRows().length == 0)
			new AccountMgmt(connection).modifyElement(idAccount, fieldLogin.getText(), fieldPassword.getText(), manager, fieldFirstname.getText(), fieldLastname.getText(), null);
		else
			new AccountMgmt(connection).modifyElement(idAccount, fieldLogin.getText(), fieldPassword.getText(), manager, fieldFirstname.getText(), fieldLastname.getText(), getIdClassesTab());
		JOptionPane.showMessageDialog(null, "Account is successfully modified !", "Modification of account", JOptionPane.INFORMATION_MESSAGE);
	}
	
	private boolean testFields()
	{
		if(fieldLogin.getText().isEmpty() == true || fieldPassword.getText().isEmpty() == true || fieldFirstname.getText().isEmpty() == true || fieldLastname.getText().isEmpty() == true)
		{
			JOptionPane.showMessageDialog(null, "Please complete all fields or choice at least one student group.", "Empty field(s)", JOptionPane.INFORMATION_MESSAGE);
			return false;
		}
		else
			return true;
	}
	
	private boolean verifyLogin() throws CheckDataException, LoadDriverException
	{
			// Test login => doit etre unique dans la DB
		MyTableModel resultModel = new AccountMgmt(connection).checkLogin(fieldLogin.getText());
		
		if(resultModel.getRowCount() == 0)
			return true;
		else
		{
			JOptionPane.showMessageDialog(null, "The specified login already exists !", "Incorrect Login", JOptionPane.ERROR_MESSAGE);
			return false;
		}
	}
	
	
	private void putInformationsIntoFields() throws CheckDataException, LoadDriverException
	{
		// Recuperation des donnees
		// SELECT id, login, password, manager, firstname, lastname, id
		MyTableModel studInfoModel = new AccountMgmt(connection).selectOneElement(idAccount);
		
		// Garnissage des champs
		accountLogin = (String)studInfoModel.getValueAt(0, 1);
		fieldLogin.setText((String)studInfoModel.getValueAt(0, 1));
		fieldPassword.setText((String)studInfoModel.getValueAt(0, 2));
		fieldFirstname.setText((String)studInfoModel.getValueAt(0, 4));
		fieldLastname.setText((String)studInfoModel.getValueAt(0, 5));
		
		if((boolean)studInfoModel.getValueAt(0, 3) == true)
			checkBoxManager.setSelected(true);
	}
	
	private ArrayList getIdClassesTab()
	{
		ArrayList<Integer> idCoursesArray = new ArrayList<Integer>();
		int[] indexCoursesSelected = tableRight.getSelectedRows();
		
		for(int i = 0; i < indexCoursesSelected.length; i++)
		{
			idCoursesArray.add((int)(GeneralInformation.getCourseLeftModel().getValueAt(indexCoursesSelected[i], 1)));
			System.out.println(idCoursesArray.get(i));
		}

		return idCoursesArray;
	}
	
	public JButton getButtonDone(){return buttonDone;}
	public int getIdAccount(){return idAccount;}
	public JTextField getFieldLogin(){return fieldLogin;}
	public JTextField getFieldPassword(){return fieldPassword;}
	public JTextField getFieldFirstname(){return fieldFirstname;}
	public JTextField getFieldLastname(){return fieldLastname;}
	public JCheckBox getBoxManager(){return checkBoxManager;}
	public JScrollPane getStudentTable(){return scrollTable;}
}